package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.TrainCarriage;
import com.jiawa.train.business.domain.TrainSeat;
import com.jiawa.train.business.enums.SeatColEnum;
import com.jiawa.train.business.mapper.TrainSeatMapper;
import com.jiawa.train.business.req.TrainSeatQueryReq;
import com.jiawa.train.business.req.TrainSeatSaveReq;
import com.jiawa.train.business.resp.TrainSeatQueryResp;
import com.jiawa.train.business.service.TrainCarriageService;
import com.jiawa.train.business.service.TrainSeatService;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TrainSeatServiceImpl extends ServiceImpl<TrainSeatMapper, TrainSeat> implements TrainSeatService {
    private static final Logger LOG = LoggerFactory.getLogger(TrainSeatServiceImpl.class);

    @Resource
    private TrainCarriageService trainCarriageService;

    public void save(TrainSeatSaveReq req) {
        DateTime now = DateTime.now();
        TrainSeat trainSeat = BeanUtil.copyProperties(req, TrainSeat.class);
        if (ObjectUtil.isNull(trainSeat.getId())) {
            trainSeat.setId(SnowUtil.getSnowflakeNextId());
            trainSeat.setCreateTime(now);
            trainSeat.setUpdateTime(now);
            this.save(trainSeat);
        } else {
            trainSeat.setUpdateTime(now);
            this.updateById(trainSeat);
        }
    }

    public PageResp<TrainSeatQueryResp> queryList(TrainSeatQueryReq req) {
        LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(TrainSeat::getTrainCode)
                .orderByAsc(TrainSeat::getCarriageIndex)
                .orderByAsc(TrainSeat::getCarriageSeatIndex);
        if (ObjectUtil.isNotEmpty(req.getTrainCode())) {
            wrapper.eq(TrainSeat::getTrainCode, req.getTrainCode());
        }
        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        Page<TrainSeat> page = new Page<>(req.getPage(), req.getSize());
        Page<TrainSeat> trainSeatPage = this.page(page, wrapper);
        LOG.info("总行数：{}", trainSeatPage.getTotal());
        LOG.info("总页数：{}", trainSeatPage.getPages());
        List<TrainSeatQueryResp> list = BeanUtil.copyToList(trainSeatPage.getRecords(), TrainSeatQueryResp.class);
        PageResp<TrainSeatQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(trainSeatPage.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        this.removeById(id);
    }

    //批量插入的问题需要考虑事物
    @Transactional
    public void genTrainSeat(String trainCode) {
        // 清空当前车次的所有座位记录
        LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TrainSeat::getTrainCode, trainCode);
        this.remove(wrapper);

        // 查找当前车次的所有车厢
        List<TrainCarriage> carriages = trainCarriageService.selectByTrainCode(trainCode);
        LOG.info("当前车次下的车厢数：{}", carriages.size());

        // 循环生成车次的所有车厢
        for (TrainCarriage carriage : carriages) {

            // 拿到车厢数据：行数、座位类型(列数)
            Integer rowCount = carriage.getRowCount();
            String seatType = carriage.getSeatType();
            Integer seatCount = carriage.getSeatCount();
            Integer index = carriage.getIndex();
            DateTime now = DateTime.now();
            for (int row = 1; row <= rowCount; row++) {
                //循环行
                for (SeatColEnum seatColEnum : SeatColEnum.values()) {
                    //循环列
                    TrainSeat trainSeat = new TrainSeat();
                    trainSeat.setId(SnowUtil.getSnowflakeNextId());
                    trainSeat.setTrainCode(trainCode);
                    trainSeat.setCarriageIndex(index);
                    //Hutool包strUtil填充，
                    trainSeat.setRow(StrUtil.fillBefore(String.valueOf(row), '0', 2));
                    trainSeat.setCol(seatColEnum.getCode());
                    trainSeat.setSeatType(seatType);
                    trainSeat.setCarriageSeatIndex(seatCount++);
                    trainSeat.setCreateTime(now);
                    trainSeat.setUpdateTime(now);
                    this.save(trainSeat);
                }
            }
        }
    }

    public List<TrainSeat> selectByTrainCode(String trainCode) {
        LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TrainSeat::getTrainCode, trainCode)
                .orderByAsc(TrainSeat::getCarriageIndex)
                .orderByAsc(TrainSeat::getCarriageSeatIndex);
        return this.list(wrapper);
    }
} 